package cn.itrip.auth.controller;

import cn.itrip.auth.exception.RedisException;
import cn.itrip.auth.exception.TokenException;
import cn.itrip.auth.exception.TokenGenerateException;
import cn.itrip.auth.exception.TokenTimeProtectedException;
import cn.itrip.auth.service.TokenService;
import cn.itrip.beans.dto.Dto;
import cn.itrip.beans.vo.ItripTokenVO;
import cn.itrip.common.DtoUtil;
import cn.itrip.common.ErrorCode;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;

/**
 * @Author: jxm
 * @Description:
 * @Date: 2020/3/13 21:50
 * @Version: 1.0
 */
@Controller
@RequestMapping("/api")
public class TokenController {

    @Resource
    private TokenService tokenService;

    /**
     * token置换
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/reToken",method = RequestMethod.POST,produces = "application/json")
    @ResponseBody
    public Dto refreshToken(HttpServletRequest request){
        String token = request.getHeader("token");
        String agent = request.getHeader("user-agent");
        ItripTokenVO tokenVO = null;
        try {
            tokenVO = tokenService.refreshToken(token,agent);
        } catch (TokenException e) {
            e.printStackTrace();
            return DtoUtil.returnFail("token无效",ErrorCode.AUTH_TOKEN_INVALID);
        } catch (TokenTimeProtectedException e) {
            e.printStackTrace();
            return DtoUtil.returnFail("token置换时间保护",ErrorCode.AUTH_REPLACEMENT_TIME_PROTECTE);
        } catch (ParseException e) {
            e.printStackTrace();
            return DtoUtil.returnFail("token验证失败",ErrorCode.AUTH_TOKEN_INVALID);
        } catch (TokenGenerateException e) {
            e.printStackTrace();
            return DtoUtil.returnFail("token生成失败",ErrorCode.AUTH_UNKNOWN);
        } catch (RedisException e) {
            e.printStackTrace();
            return DtoUtil.returnFail("token保存失败",ErrorCode.AUTH_UNKNOWN);
        }
        return DtoUtil.returnDataSuccess(tokenVO);
    }
}
